package com.jfee.dds.rest;

import com.jfee.dds.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Slf4j
public class BaseController {

    /**
     * 运行异常
     */
    @ExceptionHandler(RuntimeException.class)
    public void runtimeException(RuntimeException runtimeException, HttpServletResponse response) {
        Result res = new Result();
        res.setCodeAndMsg(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, runtimeException.getLocalizedMessage());
        PrintWriter out = null;
        try {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            out = response.getWriter();
            out.write(res.toJSONString());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
